package com.blb.demo2;

import java.util.ArrayList;
import java.util.List;

/**
 * 包子铺
 */
public class BaoZiPu {
    //上限
    public static final int MAX_COUNT=100;
    //包子缓冲区
    private List<Baozi> baoziList=new ArrayList<>();

    /**
     * 做包子
     */
    public synchronized void makeBaozi(){

        //判断缓冲区是否满了
        if (baoziList.size()==MAX_COUNT){
            System.out.println("包子铺满了，生产者等待");
            //让线程等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            //通知消费者来消费
            this.notifyAll();
        }
        //创建包子存入缓冲区
        Baozi baozi=new Baozi(baoziList.size());
        System.out.println(Thread.currentThread().getName()+"做了"+baozi);
        baoziList.add(baozi);
    }

    /**
     * 卖包子
     */
    public synchronized void sellBaozi(){
        if (baoziList.size()==0){
            //让线程等待
            System.out.println("包子铺空了   "+Thread.currentThread().getName()+"   等待");
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            //通知消费者消费
            this.notifyAll();
        }
        if (baoziList.size()>0){
            Baozi baozi = baoziList.remove(0);
            System.out.println(Thread.currentThread().getName()+"吃了"+baozi);
        }


    }



}
